<template>
  <section class="component hold-court-step">
    <el-form :model="formData" :rules="needErrorMsg? rules:{}" ref="hold-court-step-form" label-width="100px">
      <el-form-item label="开庭时间：" prop="openTime">
        <el-date-picker :disabled="isDetail" v-model="formData.openTime" type="datetime" placeholder="选择日期时间" :picker-options="$common.datePickDisabledDate(1)">
        </el-date-picker>
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <el-form-item label="开庭地点：" prop="openAddr">
            <el-input :disabled="isDetail" v-model="formData.openAddr" style="width: 98%" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="开庭人：" prop="openPerson">
            <el-input :disabled="isDetail" v-model="formData.openPerson" maxlength="20"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审判法官/仲裁员：" prop="judgeName">
            <el-input :disabled="isDetail" v-model="formData.judgeName" maxlength="20"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="法官/仲裁员电话：" prop="judgeTel">
            <el-input :disabled="isDetail" v-model="formData.judgeTel" maxlength="11"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="庭审结果：" prop="trialResult">
            <el-select :disabled="isDetail" v-model="formData.trialResult">
              <el-option v-for="{index,name,code} in $dict.getDictData('CourtTrialResults')" :key="index" :label="name" :value="code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="法律文书收到日：" prop="documentReceiveDay">
            <el-date-picker :disabled="isDetail" v-model="formData.documentReceiveDay" type="date" placeholder="选择日期" :picker-options="$common.datePickDisabledDate(1)">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="执行时效日期：" prop="prescriptionDate">
            <el-date-picker :disabled="isDetail" v-model="formData.prescriptionDate" type="date" placeholder="选择日期" :picker-options="$common.datePickDisabledDate(1)">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="开庭备注：" prop="openRemark">
        <el-input :disabled="isDetail" type="textarea" v-model="formData.openRemark" maxlength="500" show-word-limit></el-input>
      </el-form-item>
    </el-form>
    <div class="text-center">
      <el-button @click="previousStepEmit">上一步</el-button>
      <el-button v-if="isShow" @click="submit" :loading="submitLoading">保存</el-button>
      <el-button @click="nextStepEmit">下一步</el-button>
      <!-- <el-button @click="finishCaseEmit">结案</el-button> -->
    </div>

  </section>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { Prop, Emit, Watch } from "vue-property-decorator";
import { Dependencies } from '~/core/decorator';
import { CaseOperatorPageService } from '~/services/domain-service/case-operator-page.service';
import { State, Action, Getter, namespace } from "vuex-class";
import { MENU_CHANNEL } from "~/config/enum.config";
import { CaseLegalRecordService } from '~/services/domain-service/case-legalRecord.service';
const CollectionExecutionModule = namespace('collection-execution');

@Component({
  components: {}
})

export default class HoldCourtStep extends Vue {
  @Dependencies(CaseOperatorPageService)
  private caseOperatorPageService: CaseOperatorPageService;
  @CollectionExecutionModule.State private caseId;
  @CollectionExecutionModule.State private menuChannel;
  @CollectionExecutionModule.State private otherData;
  @CollectionExecutionModule.Mutation private updateCurrentSavedStep;
  
  @Dependencies(CaseLegalRecordService) private caseLegalRecordService: CaseLegalRecordService;
  @Prop({ type: String, required: false })
  private id: string;

  @Prop({ type: String })
  private operatorId;

  @State
  private userData: any;

  @Prop({type:Boolean}) private isDetail

  @Prop({ type: Boolean }) private needErrorMsg

  private formData: any = {
    legalStage: "OPEN",
    legalStatus: "COME_UP",
    id: "",
    openTime: "",
    openAddr: "",
    openPerson: "",
    judgeName: "",
    judgeTel: "",
    trialResult: "MEDIATE",
    documentReceiveDay: "",
    prescriptionDate: "",
    openRemark: "",
  }
  private rules: any = {
    openTime: [{ required: true, message: "请输入开庭时间" }],
    openAddr: [{ required: true, message: "请输入开庭地点" }],
    openPerson: [{ required: true, message: "请输入开庭人" }],
    documentReceiveDay: [{ required: true, message: "请选择法律文书收到日", trigger: 'change' }],
    judgeTel: { validator: this.$validator.phoneNumber, trigger: 'blur' }
  }
  private submitLoading: boolean = false

  @Emit('nextStep')
  private nextStepEmit() { }

  @Emit('previousStep')
  private previousStepEmit() { }

  @Emit('finishCase')
  private finishCaseEmit() { }

  @Emit('emitSuccess')
  private emitSuccess() {
    if (this.id) {
      this.showLegalInfoById(this.id);
    } else {
      // this.showLegalInfo();
    }
  }
  private get isShow() {
    const arr = [MENU_CHANNEL.Legal_personal, MENU_CHANNEL.Legal_team, MENU_CHANNEL.Assist_legal]
    if (arr.find(v => this.menuChannel === v)) {
      // 添加催记显示保存按钮 或编辑催记 与该登录用户一致显示
      if (!this.operatorId || this.operatorId === this.userData.id) return true
      else return false
    }
    return false
  }

  private showLegalInfoById(id) {
    if (id) {
      const vals = { "caseLegalRecordId": id }
      // 列表详情
      this.caseLegalRecordService
        .getCaseLegalRecordById(vals)
        .subscribe(
          (data) => {
            if (data) {
              this.formData.id = data.id;
              this.formData.openTime = data.openTime;
              this.formData.openAddr = data.openAddr;
              // if (data.isComeUp === "YES") {
              //   this.formData.openPerson = data.openPerson;
              // }
              this.formData.openPerson = data.openPerson;
              this.formData.judgeName = data.judgeName;
              this.formData.judgeTel = data.judgeTel;
              this.formData.trialResult = data.trialResult;
              this.formData.documentReceiveDay = data.documentReceiveDay;
              this.formData.prescriptionDate = data.prescriptionDate;
              this.formData.openRemark = data.openRemark;
            }
          },
          (err) => {

          },
        );
    }
  }
  private mounted() {
    if (this.id) {
      this.showLegalInfoById(this.id)
    } else {
      this.formData.openPerson = this.userData.realName;
      // this.showLegalInfo();
    }
  }
  private showLegalInfo() {
    //查询上一条催记是否结案，回显数据
    this.caseOperatorPageService
      .queryUnClossCaseLegalRecord(this.caseId)
      .subscribe(
        (data) => {
          if (data) {
            this.formData.id = data.id;
            this.formData.openTime = data.openTime;
            this.formData.openAddr = data.openAddr;
            // if (data.isComeUp === "YES") {
            //   this.formData.openPerson = data.openPerson;
            // }
            this.formData.openPerson = data.openPerson;
            this.formData.judgeName = data.judgeName;
            this.formData.judgeTel = data.judgeTel;
            this.formData.trialResult = data.trialResult;
            this.formData.documentReceiveDay = data.documentReceiveDay;
            this.formData.prescriptionDate = data.prescriptionDate;
            this.formData.openRemark = data.openRemark;
          }
        },
        (err) => {

        },
      );
  }

  private setCurrentFormDataVal (step) {
    this.updateCurrentSavedStep(step)
    sessionStorage.setItem('currentFormDataVal', JSON.stringify(this.formData))
    setTimeout(() => {
      // this.formData = JSON.parse(sessionStorage.getItem('currentFormDataVal') || "") || {}
      const formData = JSON.parse(sessionStorage.getItem('currentFormDataVal') || "") || {}

      this.toInitData(formData)
    }, 300);
  }

  private toInitData (data) {
    const  formData = { ...data }
    for (const key in this.formData) {
      if (!['openPerson', 'trialResult'].includes(key)) {
        formData[key] = ''
      }
    }
    this.formData = formData
  }

  private submit() {
    const form: any = this.$refs["hold-court-step-form"];
    form.validate(valid => {
      if (!valid) return false;
      if (this.menuChannel === MENU_CHANNEL.Assist_legal) {
        this.formData.assistId = this.otherData.assistId;
      }
      if (this.formData.openTime) this.formData.openTime = this.$filter.dateTimeFormat(this.formData.openTime)

      if (this.formData.prescriptionDate) this.formData.prescriptionDate = this.$filter.dateFormat(this.formData.prescriptionDate)

      if (this.formData.documentReceiveDay) this.formData.documentReceiveDay = this.$filter.dateFormat(this.formData.documentReceiveDay)

      this.formData.caseId = this.caseId;
      // this.formData.caseLegalRecordId = this.caseId;
      // this.formData.caseInfoRecordId = this.caseId;
      if (this.caseId && this.id) {
        this.setCurrentFormDataVal(1)
        this.caseLegalRecordService.editCaseLegalRecord(this.formData).subscribe(
            (data) => {
              form.resetFields();
              this.formData.id = "";
              this.emitSuccess();
              this.$message.success('法催催记立案已修改成功');
            },
            (err) => {
              this.submitLoading = false;
            },
          );
      } else {
        this.setCurrentFormDataVal(1)
        this.caseLegalRecordService
          .addCaseLegalRecord(this.formData)
          .subscribe(
            (data) => {
              form.resetFields();
              this.formData.id = "";
              this.emitSuccess();
              this.$message.success('法催催记开庭已添加成功，如需修改请在法务详情中进行修改');
            },
            (err) => {
              this.submitLoading = false;
            },
          );
      }
    });
  }
}

</script>